package com.xbongbong.paas.manager.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.manager.PushManager;
import com.xbongbong.paas.pojo.dto.ImmediatelyPushDTO;
import com.xbongbong.paas.pojo.vo.ImmediatelyPushVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.constant.BasicConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;

/**
 * @author kaka
 * @time 2018-10-10 16:52
 */
@Service("pushManager")
public class PushManagerImpl implements PushManager {

    private static final Logger LOG = LoggerFactory.getLogger(PushManagerImpl.class);

    public static final String IMMEDIATELY_PUSH_URL = "push/immediatelyPush.html";

    @Resource
    private RestTemplate restTemplate;
    @Resource
    private ProBaseConfig proBaseConfig;

    @Override
    public ImmediatelyPushVO immediatelyPush(ImmediatelyPushDTO immediatelyPushDTO) throws XbbException {

        ImmediatelyPushVO immediatelyPushVO = new ImmediatelyPushVO();

        // 立即推送地址
        String pushUrl = proBaseConfig.getProjectDingtalkUrl() + IMMEDIATELY_PUSH_URL;
        Map<String, Object> pushParams = BeanUtil.convertBean2Map(immediatelyPushDTO, true);

        MultiValueMap<String, String> postParameters = new LinkedMultiValueMap<>();
        for (Map.Entry entry : pushParams.entrySet()) {
            postParameters.add((String)entry.getKey(), String.valueOf(entry.getValue()));
        }
        postParameters.add("userIdList", JSON.toJSONString(immediatelyPushDTO.getUserIdList()));
        postParameters.add("key", BasicConstant.TASK_SECRET_KEY);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(postParameters, headers);

        try {
            // TODO 改异步
            String respStr = restTemplate.postForObject(pushUrl, requestEntity, String.class);
            if (StringUtil.isEmpty(respStr)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
            } else {
                JSONObject respJson = JSON.parseObject(respStr);
                if (respJson != null && respJson.getInteger("code") != null && respJson.getInteger("code").equals(ErrorCodeEnum.API_SUCCESS.getCode())) {
                    // 成功逻辑 TODO 目前没有其他东西
                } else {
                    if (Objects.nonNull(respJson)) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001.getCode(), respJson.getString("msg"));
                    }
                }
            }
        } catch (XbbException xe) {
            throw xe;
        } catch (Exception e) {
            LOG.error("PushManagerImpl.immediatelyPush 执行出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }

        return immediatelyPushVO;
    }
}
